<?php


namespace app\back\model;


use think\facade\Db;
use think\response\Json;
use \Exception;

class UserModel
{
    private static $_table = 'user'; // 老板员工表
    private static $_goodsTable = 'goods'; // 商品表
    private static $_goodsUnitTable = 'goods_unit'; // 商品单位表
    private static $_userTable = 'user'; // 用户表
    private static $_centerTable = 'organization'; // 分拣中心表
    private static $_companyTable = 'company'; // 公司表
    private static $_companyAddressTable = 'company_address'; // 公司地址表
    private static $_adminTable = 'admin'; // 管理员表
    private static $_configTable = 'eb_config'; // 配置表
    private static $_companyCenterTable = 'company_center'; // 公司-分拣中心中间表

    /**获取老板列表
     * @param $input
     * @param $info
     * @return Json
     */
    public static function getBossList($input,$info)
    {
        try {
            $map = [
                ['u.admin_id', '=', $info['id']],
                ['u.role_type', '=', 1]
            ];
            if ($input['status'] !== '') {
                $map[] = ['u.status', '=', $input['status']];
            } else {
                $map[] = ['u.status', 'in', [1,2]];
            }
            if ($input['is_adopt'] !== '') {
                $map[] = ['u.is_adopt', '=', $input['is_adopt']];
            }
            if ($input['name'] !== '') $map[] = ['u.name', 'like', "%{$input['name']}%"];
            $field = 'u.id,u.username,u.name,u.phone,u.gender,u.status,u.is_adopt,u.create_time,c.name as company_name';
            $table = Db::table(self::$_table)->alias('u')
                ->leftJoin([self::$_companyTable => 'c'], 'c.id = u.group_id')
                ->where($map)->field($field);
            $count = $table->count();
            if ($count == 0) return jsonSuccess('暂无数据', ['count' => 0,'list' => []]);
            $list = $table->page($input['page'], $input['limit'])->order('u.create_time', 'desc')->select()->toArray();
            return jsonSuccess('获取成功', ['count' => $count, 'list' => $list]);
        } catch (Exception $e) {
            return jsonFail('服务内部错误~');
        }
    }

    /**审核老板
     * @param $input
     * @param $info
     * @return Json
     */
    public static function checkBoss($input,$info)
    {
        try {
            if ($input['is_adopt'] == 1) {
                // 检测公司是否绑定分拣中心
                $userTable = self::$_table;
                $count = Db::table(self::$_companyCenterTable)->whereRaw("group_id = (select group_id from {$userTable} where id = {$input['id']})")->count();
                if ($count == 0) return jsonFail('公司先绑定分拣中心然后再来审核');
            }
            $map = [
                ['id', '=', $input['id']],
                ['admin_id', '=', $info['id']],
                ['role_type', '=', 1],
                ['status', 'in', '1,2']
            ];
            $rtn = Db::table(self::$_table)->where($map)->update(['is_adopt' => $input['is_adopt']]);
            if ($rtn) return jsonSuccess('操作成功');
            return jsonFail('操作失败,刷新页面重试');
        } catch (Exception $e) {
            return jsonFail('服务内部错误~');
        }
    }

    /**修改老板状态
     * @param $input
     * @param $info
     * @return Json
     */
    public static function changeBossStatus($input,$info)
    {
        try {
            $map = [
                ['id', '=', $input['id']],
                ['admin_id', '=', $info['id']],
                ['role_type', '=', 1],
                ['status','=', $input['status'] == 1? 2:1]
            ];
            $rtn = Db::table(self::$_table)->where($map)->update(['status' => $input['status']]);
            if ($rtn) return jsonSuccess('操作成功');
            return jsonFail('操作失败,刷新页面重试');
        } catch (Exception $e) {
            return jsonFail('服务内部错误~');
        }
    }

    /**获取公司地址
     * @param $input
     * @param $info
     * @return Json
     */
    public static function getAddressSimple($input,$info)
    {
        try {
            $map = [
                ['u.id', '=', $input['id']],
                ['u.admin_id', '=', $info['id']],
                ['ca.status', '=', 1],
            ];
            $list = Db::table(self::$_table)->alias('u')
                ->join([self::$_companyTable =>'c'], 'c.id = u.group_id')
                ->join([self::$_companyAddressTable =>'ca'], 'ca.group_id = c.id')
                ->where($map)
                ->field('ca.id,concat(province,city,area,address) as address')
                ->select()->toArray();
            if ($list) return jsonSuccess('获取成功', $list);
            return jsonFail('未找到可用公司地址');
        } catch (Exception $e) {
            return jsonFail('服务内部错误~');
        }
    }

    /**代理下单
     * @param $input
     * @param $info
     * @return Json
     */
    public static function agentMakeOrder($input,$info)
    {
        $flag = false;
        try {
            $goodsData = json_decode($input['goods_data'], true);
            $goodsData = array_column($goodsData, 'goods_num', 'goods_name');
            // 查询商品信息
            $map = [
                ['g.name', 'in', array_keys($goodsData)],
                ['g.admin_id', '=', $info['id']]
            ];
            $list = Db::table(self::$_goodsTable)->alias('g')
                ->join([self::$_goodsUnitTable =>'gu'], 'gu.id = g.unit_id')
                ->join([self::$_centerTable =>'c'], 'c.id = g.center_id')
                ->field('g.id,g.name,gu.name as unit_name,gu.type as unit_type,c.name as center_name,stock,g.status,g.image,g.price,g.center_id')
                ->where($map)
                ->select()->toArray();
            if (count($list) != count($goodsData)) return jsonFail('存在不合法的商品');
            // 用户信息
            $map = [
                ['u.id', '=', $input['id']],
                ['u.admin_id', '=', $info['id']]
            ];
            $user = Db::table(self::$_userTable)->alias('u')
                ->join([self::$_companyTable => 'c'], 'c.id = u.group_id')
                ->field('u.is_adopt,u.pid,u.name,u.phone,u.role_type,c.is_believe,group_id')
                ->where($map)
                ->find();
            if (!$user) jsonFail('未找到用户信息');
            if ($user['is_adopt'] != 1) return jsonFail('暂未通过审核或审核未通过，不能生成订单');
            if ($user['is_believe'] != 1) return jsonFail('非授信公司，不能生成订单');
            // 获取配置
            $map = [
                ['admin_id', '=', $info['id']],
                ['name', '=', 'ratio_proportion']
            ];
            $config = Db::table(self::$_configTable)->field('value')->where($map)->find();
            if (!$config) return jsonFail('系统配置错误');
            $config['ratio_proportion'] = $config['value'];
            $adminTable = self::$_adminTable;
            $sql = "(select pid,percent,level from {$adminTable} where id = {$info['id']} and `level` = 2)
            union
            (select pid,percent,level from {$adminTable} where id = ((select pid from {$adminTable} where id = {$info['id']} and `level` = 2)) and `level` = 1)
            union
            (select pid,percent,level from {$adminTable} where id = ((select pid from {$adminTable} where id = ((select pid from {$adminTable} where id = {$info['id']} and `level` = 2)) and `level` = 1)) and `level` = 0)";
            $percentArr = Db::query($sql);
            if (count($percentArr) != 3) return jsonFail('运营商配置错误');
            foreach ($percentArr as $v) {
                if ($v['level'] == 2) {
                    $driver_percent = $v;
                    continue;
                }
                if ($v['level'] == 1) {
                    $primary_percent = $v;
                    continue;
                }
                if ($v['level'] == 0) {
                    $company_percent = $v;
                    continue;
                }
            }
            $master_order_no = create_order_no();//主订单号
            $code = substr(microtime(), -6);//生成提货码
            $change_message = '授信用户创建订单成功，等待出库！';
            Db::startTrans();
            $flag = true;
            foreach ($list as $key => $value) {
                $totalPrice = $goodsData[$value['name']] * $value['price'];
                $orderIns = Db::table('order')->insertGetId([
                    'group_id' => $user['group_id'],
                    'role_type' => $user['role_type'],
                    'mastr_order_no' => $master_order_no,
                    'order_no' => build_order_no(),//生成子订单号
                    'goods_data' => json_encode($value),
                    'goods_id' => $value['id'],
                    'total_price' => $totalPrice,
                    'pid' => $user['pid'],
                    'pid_price' => $user['pid'] != 0 ? round($totalPrice * ($config['ratio_proportion'] / 100), 2) : 0,
                    'company_price' => round($totalPrice * ($company_percent['percent'] / 100), 2),//公司反比
                    'primary_price' => round($totalPrice * ($primary_percent['percent'] / 100), 2),//一级反比
                    'driver_price' => round($totalPrice* ($driver_percent  ['percent'] / 100), 2),//司机路费
                    'num' => $goodsData[$value['name']],
                    'is_believe' => 1,
                    'user_id' => $input['id'],
                    'address_id' => $input['address_id'],
                    'admin_id' => $info['id'],
                    'center_id' => $value['center_id'],
                    'center_name' => $value['center_name'],
                    'remark' => '代理下单',
                    'code' => $code,
                    'is_pay' => 1,
                    'pay_type' => 2,
                    'create_time' => time(),
                    'pay_time' => time(),
                ]);
                $red = Db::table('order_status')->insertGetId([
                    'oid' => $orderIns,
                    'change_message' => $change_message,
                    'name' => $user['name'],
                    'phone' => $user['phone'],
                    'role_type' => $user['role_type'] == 1 ? '老板' : '员工',
                    'create_time' => time(),
                ]);
                if ($red == false) {
                    Db::rollback();
                    return jsonFail('下单失败', $red);
                }
                $red = Db::execute("update goods  set stock=stock- " . $goodsData[$value['name']] . ",ice_stock=ice_stock+{$goodsData[$value['name']]},sales = sales+{$goodsData[$value['name']]} where id=" . $value['id']);
                if ($red == false) {
                    Db::rollback();
                    return jsonFail('减少库存失败', $red);
                }
            }
            Db::commit();
            return jsonSuccess('代理下单成功');
        } catch (Exception $e) {
            if ($flag == true) Db::rollback();
            return jsonFail('系统错误~', $e->getMessage());
        }
    }
}